<template>
  <div>
    <el-dialog
      title="添加子设备"
      :visible.sync="dialogVisible"
      width="500px"
      :before-close="closeDialog"
      :close-on-click-modal="false"
      append-to-body
    >
      <el-form :model="addForm" :rules="rules" ref="refForm" label-width="0">
        <div class="titles">
          <div class="ant-col" style="flex: 7">
            <span class="red-star">*</span>设备编码
          </div>

          <div class="ant-col" style="flex: 4; margin-left: 60px">位置标记</div>
          <div style="position: absolute; right: 0"></div>
        </div>
        <div
          v-for="(item, index) in addForm.formData"
          :key="index"
          class="list"
        >
          <el-form-item
            size="small"
            label=""
            :prop="`formData.${index}.imei`"
            :rules="rules.imei"
            style="flex: 7"
          >
            <el-input
              clearable
              oninput="value=value.replace(/[\u4e00-\u9fa5]/g,'')"
              @blur="item.imei = $event.target.value"
              v-model="item.imei"
              placeholder="请输入设备编码"
              maxlength="25"
              @change="changeImei($event, index)"
            ></el-input>
            <!--      -->
          </el-form-item>
          <el-form-item
            size="small"
            label=""
            style="flex: 4; margin-left: 60px"
          >
            <div style="display: flex; align-items: center">
              <el-button
                size="small"
                type="primary"
                @click="sign(index)"
                icon="el-icon-location-outline"
                >{{ item.nameMark }}</el-button
              >
            </div>
          </el-form-item>
          <el-form-item style="position: absolute; left: 410px">
            <i
              class="el-icon-delete icon"
              @click="clickDel(index)"
              v-if="addForm.formData.length > 1"
            ></i>
            <i
              class="el-icon-circle-plus-outline icon"
              @click="clickAdd(index)"
              v-if="index === addForm.formData.length - 1"
            ></i>
          </el-form-item>
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog">取 消</el-button>
        <el-button
          size="small"
          type="primary"
          @click="submit"
          :loading="buttonLoading"
          v-preventReClick="1000"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <Ichnography ref="refIchnography" @clickMark="clickMark"></Ichnography>
  </div>
</template>

<script>
import {
  reqDeviceBindByFather,
  reqSpaceManager,
  reqFloorById,
  reqDeviceByImei,
} from "@api/api.js";
import { validateImei } from "@utils/validate";
import { mapState } from "vuex";
import loadMore from "@mixin/loadMore";
import Ichnography from "../Ichnography.vue";

export default {
  mixins: [loadMore],
  props: {
    deviceInfo: {
      type: Object,
      default: () => {},
    },
  },
  components: {
    Ichnography,
  },
  data() {
    return {
      dialogVisible: false,
      buildList: [],
      floorList: [],
      spaceList: [],
      addForm: {
        formData: [
          {
            imei: "",
            nameMark: "标记",
            mark: "",
            isEnter: false,
            isBind: false,
          },
        ],
        spaceId: "",
      },
      rules: {
        imei: [
          { required: true, message: "请输入设备编码", trigger: "blur" },
          { validator: validateImei },
        ],
      },

      clickIndex: 0,
      buttonLoading: false,
    };
  },
  computed: {
    ...mapState(["user"]),
  },
  watch: {},
  mounted() {},
  methods: {
    async changeImei(e, index) {
      console.log(e, index);
      const res = await reqDeviceByImei(e);
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      console.log(res);
      if (res.data.info && res.data.info.id) {
        this.addForm.formData[index].isEnter = true;
        if (res.data.info.tenantId && res.data.info.tenantId != 0) {
          this.addForm.formData[index].isBind = true;
          // this.$modal.notifyWarning("设备已被绑定!");
        } else {
          this.addForm.formData[index].isBind = false;
        }
      } else {
        this.addForm.formData[index].isEnter = false;
        // return this.$modal.notifyWarning(
        //   "设备未入库，请检查设备编码是否输入正确!"
        // );
      }
    },
    // 点击新增
    clickAdd() {
      if (this.addForm.formData.length >= 5)
        return this.$modal.notifyWarning("一次最多添加5台设备！");
      this.addForm.formData.push({
        imei: "",
        nameMark: "标记",
        mark: "",
        isEnter: false,
        isBind: false,
      });
    },
    clickDel(index) {
      this.addForm.formData.splice(index, 1);
    },
    async sign(index) {
      this.clickIndex = index;
      if (this.deviceInfo.spaceId == "")
        return this.$modal.notifyWarning("请先选择安装点!");
      const res = await reqFloorById(this.deviceInfo.spaceId);
      // console.log(res);
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      if (res.data.rows.image == "")
        return this.$modal.notifyWarning("当前楼层暂无平面图,请上传后操作!");
      this.$refs.refIchnography.dialogVisible = true;
      this.$refs.refIchnography.getimage(res.data.rows.image);
      if (this.addForm.formData[index].nameMark === "已标记") {
        this.$refs.refIchnography.getMark(this.addForm.formData[index].mark);
      }
    },

    // 子组件事件
    clickMark(e) {
      this.addForm.formData[this.clickIndex].mark = e;
      this.addForm.formData[this.clickIndex].nameMark = "已标记";
    },

    // 点击绑定
    submit() {
      setTimeout(() => {
        this.buttonLoading = true;
        this.$refs.refForm.validate(async (valid) => {
          if (!valid) {
            this.buttonLoading = false;
            return;
          }

          const formData = this.addForm.formData;

          const imeiList = formData.map((item) => item.imei);

          // 提示
          let flag = false;
          formData.forEach((item, index) => {
            if (!item.isEnter) {
              setTimeout(() => {
                this.$modal.notifyWarning(`第${index + 1}个设备未入库!`);
              });
              flag = true;
              return;
            }
            if (item.isBind) {
              setTimeout(() => {
                this.$modal.notifyWarning(`第${index + 1}个设备已被绑定!`);
              });
              flag = true;
              return;
            }
          });
          if (flag) return (this.buttonLoading = false);

          // 查重
          let duplicate = this.checkDuplicates(imeiList);
          if (duplicate) {
            setTimeout(() => {
              this.$modal.notifyWarning(
                `第${duplicate.index1 + 1}个和第${
                  duplicate.index2 + 1
                }个设备编码重复`
              );
            }, 0);
            return (this.buttonLoading = false);
          }

          // imei数据处理
          let imei = this.addForm.formData.reduce((acc, item) => {
            acc[item.imei] = item.mark;
            // acc[JSON.stringify(item.imei)] = item.mark;
            return acc;
          }, {});

          const res = await reqDeviceBindByFather({
            imei: imei,
            spaceId: this.deviceInfo.spaceId,
            userId: this.user.userId,
            fatherId: this.deviceInfo.id,
          });
          if (res.code !== 20000) {
            this.buttonLoading = false;
            this.$modal.notifyWarning(res.message);
            return;
          }
          this.buttonLoading = false;
          this.$modal.notifySuccess("绑定成功");
          this.closeDialog();
          this.$refs.refIchnography.closeDialog();
          this.$parent.getDataList();
        });
      }, 1000);
    },
    // 点击关闭弹框
    closeDialog() {
      this.$refs.refIchnography.closeDialog();
      this.$refs.refForm.resetFields();
      this.addForm = {
        formData: [
          {
            imei: "",
            nameMark: "标记",
            mark: "",
            isEnter: false,
            isBind: false,
          },
        ],
      };
      this.dialogVisible = false;
    },

    checkDuplicates(arr) {
      for (let i = 0; i < arr.length; i++) {
        for (let j = i + 1; j < arr.length; j++) {
          if (arr[i] === arr[j]) {
            return { index1: i, index2: j, value: arr[i] };
          }
        }
      }
      return null;
    },
  },
  deactivated() {
    if (this.$refs.refIchnography != null || this.$refs.refForm != null) {
      this.closeDialog();
    }
  },
};
</script>

<style lang="less" scoped>
@import url("../../../../views/common.less");
.titles {
  position: relative;
  font-size: 14px;
  border-bottom: 2px solid @primaryBorderColor;
  padding-bottom: 8px;
  margin: 0 3px 15px;
  display: flex;
  color: @primaryThemeTxtColor2;
  .ant-col {
    width: 160px;
    .red-star {
      color: #f56c6c;
    }
  }
}
.list {
  position: relative;
  display: flex;
  align-items: center;
  .icon {
    font-size: 20px;
    // color: #d55b67;
    color: #7367f0;
    cursor: pointer;
    padding-top: 5px;
    margin-top: 10px;
  }
  .el-icon-circle-plus-outline {
    font-size: 20px;
    margin-left: 8px;
  }
}
</style>
